import cv2
import numpy as np
import requests, json
import base64

def image_to_base64(img_np):
    img = cv2.imencode('.jpg', img_np)[1]
    img_code64 = base64.b64encode(img)
    return img_code64

def base64_to_img(base64code):
    img_data = base64.b64decode(base64code)
    img_array = np.frombuffer(img_data, np.uint8)
    img =cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
    return img

def str_to_byte(str_data):
    byte = bytes(str_data, encoding='utf8')
    return byte

def byte_to_str(byte):
    str_ = str(byte)[2:]
    return str_

def saveImg(ip, port):
    # r = requests.get('http://127.0.0.1:8080/catchImg')
    addr = 'http://' + ip + ':' + port + '/catchImg'
    try:
        r = requests.get(addr, timeout=5)
        r.status_code
        json_data = json.loads(r._content)
        byte = str_to_byte(json_data["image"])
        img = base64_to_img(byte)
        # cv2.imshow('', img)
        # cv2.waitKey()
        return img
    except requests.exceptions.RequestException as e:
        print(e)
        return None